package com.icast.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.InputFilter;
import android.text.InputType;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.icast.api.ICast;
import com.smit.dvb.CIPinInfo;

public class DialogPin extends Dialog {
	private static Context mContext;

	public DialogPin(Context context) {
		super(context);
		mContext = context;
	}

	public void initView() {
		LinearLayout linearLayoutMain = new LinearLayout(mContext);
		linearLayoutMain.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
		linearLayoutMain.setBackgroundColor(0xff333333);
		linearLayoutMain.setPadding(50, 30, 50, 30);

		CIPinInfo ciPinInfo = ICast.getCIPinInfo();
		
		TextView TitleTextView = new TextView(mContext);
		TitleTextView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		TitleTextView.setText(ciPinInfo.title);
		TitleTextView.setGravity(Gravity.CENTER);
		TitleTextView.setTextSize(30);
		linearLayoutMain.addView(TitleTextView);

		final EditText ciPinEdit = new EditText(mContext);
		if (1 == ciPinInfo.type) {
			ciPinEdit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
		} else {
			ciPinEdit.setInputType(InputType.TYPE_CLASS_NUMBER);
		}
		if (0xff != ciPinInfo.length) {
			ciPinEdit.setFilters(new InputFilter[] { new InputFilter.LengthFilter(ciPinInfo.length) });
		}
		ciPinEdit.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		ciPinEdit.setTextSize(20);
		linearLayoutMain.addView(ciPinEdit);

		Button ciPinButton = new Button(mContext);
		ciPinButton.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		ciPinButton.setText("确认");
		ciPinButton.setGravity(Gravity.CENTER);
		ciPinButton.setTextSize(20);
		ciPinButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String pin = ciPinEdit.getText().toString();
				ICast.setCIPinInfo(pin);
				dismiss();
			}
		});
		linearLayoutMain.addView(ciPinButton);

		setOnKeyListener(new DialogInterface.OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK && KeyEvent.ACTION_DOWN != event.getAction()) {
					ICast.setCIPinInfo("");
					dismiss();
					return true;
				} else {
					return false;
				}
			}
		});
		getWindow().setContentView(linearLayoutMain);
	}
}